<?php
// +----------------------------------------------------------------------
// | Description: 用户组
// +----------------------------------------------------------------------
// | Author:
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\admin\model\Common;
use app\common\traits\ActionRecordTrait;
use think\facade\Db;

class Group extends Common
{

    use ActionRecordTrait;

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'admin_group';

    /**
     * [getDataList 获取列表]
     * @param  tree 1 属性
     * @param  rules 1 二维数组
     * @param  pid 分类：0客户自定义角色,1系统默认管理角色,2客户管理角色,3人力资源管理角色(原客户),4财务管理角色(原客户),5项目管理角色,6办公管理角色,7人力资源管理角色,8财务管理角色,9项目管理员角色
     * @param  备注：原自定义角色0,人事管理角色3,财务管理角色4，划分至新客户管理角色中
     * @param  rule：types 0系统设置1工作台2客户管理3项目管理4人力资源5财务管理6商业智能(客戶)
     * @return    [array]
     */
    public function getDataList($param,$shopId,$type)
    {
        
        $list = $this->getTypeList();
        $shops=[];
        $map = [
            ['status','=',1]
        ];
        if($type ==1){
            $map[] = ['shop_id', '=', null];
        }
        if (isset($param['search']) && $param['search']) {
            $map[] = ['title', 'like', '%'.$param['search'].'%'];
        }
        if (isset($param['shopId']) && $param['shopId']) {
            $shops =$param['shopId'];
            $map[] = ['shop_id', '=', $param['shopId']];
            unset($map[1]);
        }

        if($shopId == 73782776653608){
            $list = Db::name('admin_group')->where($map)
                ->when($shopId??[], function ($query) use ($shopId){
                    return $query->where('shop_id',$shopId)->whereOr('id',2);
                })
                ->when($shops??[], function ($query) use ($shops){
                    return $query->whereOr('id',2)->whereOr('id',52);
                })->select()->toArray() ? : [];
        }else{
            $list = Db::name('admin_group')->where($map)
                ->when($shopId??[], function ($query) use ($shopId){
                    return $query->where('shop_id',$shopId)->whereOr('id',2);
                })
                ->when($shops??[], function ($query) use ($shops){
                    return $query->whereOr('id',2)->whereOr('id',52)->whereOr('id',76)->whereOr('id',156);
                })->select()->toArray() ? : [];
        }
        if($list){
            foreach($list as $k =>  $v){
                if($v['front_menus']){
                    $list[$k]['front_menus'] = stringToArray($v['front_menus']);
                }
            }

        }

       // $list = Db::name('admin_group')->where(['status' => 1])->select()->toArray() ? : [];
        return $list ? : [];
    }

    /**
     * 添加
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-08-03 14:46
     */
    public function addData(array $request,$shopId): bool
    {
        $title = isset($request['title']) && trim($request['title']) ? trim($request['title']) : '';
        if (!$title) {
            $this->error = '请填写角色名称';
            return false;
        }
        Db::startTrans();
        try {
            $data = [
                'pid'    => 0,
                'title'  => $title,
                'rules'  => '',
                'menus'  => '',
                'status' => 1,
                'types'  => 0,
                'shop_id'  => $shopId ??null
            ];
            $groupId = $this->insertGetId($data);
            if (!$groupId) {
                throw new \Exception('添加角色失败');
            }
            $dataArr['group_data'] = $data;
            $market =empty($request['market'])?[]:$request['market'];
            $marketView =empty($request['market_view'])?[]:$request['market_view'];
            $authField = ['leads', 'customer','market','market_view','business', 'order', 'sample', 'min_user'];
            foreach ($authField as $key => $val) {
                if (array_key_exists($val, $request) && !in_array(intval($request[$val]), [1, 2, 3, 4, 5])) {
                    $request[$val] = in_array(intval($request[$val]), [1, 2, 3, 4, 5]) ? intval($request[$val]) : 1;
                }
            }
            // 更新角色数据权限
            $data = [
                'group_id'    => $groupId,
                'leads'       => $request['leads'] ?? 1,
                'customer'    => $request['customer'] ?? 1,
                'business'    => $request['business'] ?? 1,
                'order'       => $request['order'] ?? 1,
                'sample'      => $request['sample'] ?? 1,
                'min_user'    => $request['min_user'] ?? 1,
                'market'    => json_encode($market,true),
                'market_view'    =>  json_encode($marketView,true),
                'create_time' => time(),
                'update_time' => time()
            ];
            $insertId = Db::name('admin_data_auth')->insertGetId($data);
            if (!$insertId) {
                throw new \Exception('添加角色数据权限失败');
            }
            $dataArr['data_auth_data'] = $data;
            $dataArr['request_data']   = $request;

            // 添加操作记录
            $logCode = json_encode($dataArr, JSON_UNESCAPED_UNICODE);
            $this->addActionRecord($request['user_id'], 'admin_group_create', $groupId, '创建了角色', 'admin', 'group', $logCode);

            Db::commit();

            $this->error = '添加成功';
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
        }

        return false;
    }

    /**
     * 编辑
     * @param  array $param 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-08-03 14:46
     */
    public function saveData(array $param): bool
    {
        try {
            $request  = $param;
            $groupId = isset($param['group_id']) && intval($param['group_id']) ? intval($param['group_id']) : 0;
            $dataInfo = $this->find($groupId);
            if(!$dataInfo){
                $this->error = '该角色不存在或已删除';
                return false;
            }
            # 处理编辑时，前端可能不传父id的问题（admin_menu表level为1的主键）
            if (isset($param['menus']) && !empty($param['menus'])) {
                $param['menus'] = arrayToString($param['menus']);
                $param['front_menus'] =  arrayToString(stringToArray($param['menus']));
                $rulesParam    = stringToArray($param['menus']);
                $rulesParamStr = implode(',', $rulesParam);
                $rulesList     = Db::name('admin_menu')->field(['id', 'level', 'pid'])->whereIn('id', $rulesParamStr)->select()->toArray();
                foreach ($rulesList AS $key => $value) {
                    if (!empty($value['level']) && $value['level'] == 2) $rulesParam[] = $value['pid'];
                    if (!empty($value['level']) && $value['level'] == 3) {
                        $rulesParam[] = $value['pid'];
                        $rulesParam[] = Db::name('admin_menu')->where('id', $value['pid'])->value('pid');
                    }
                    if (!empty($value['level']) && $value['level'] == 4) {
                        $rulesParam[] = $value['pid'];
                        $rulesParam[] =  $secondLevelMenuIds = Db::name('admin_menu')->where('id', $value['pid'])->value('pid');
                        $rulesParam[] = Db::name('admin_menu')->where('id', $secondLevelMenuIds)->value('pid');
                    }
                }
                $param['menus'] = arrayToString(array_unique($rulesParam));


            }
            //编辑角色
            if(!isset($param['menus'])){
                unset($param['front_menus'],$param['rules']);
            }
            //编辑权限设置为空
            if(isset($param['menus']) && (empty($param['menus']) || empty(arrayToString($param['menus'])))){
                $param['front_menus']  =  $param['menus'] = $param['rules'] = '';
            }
            if(isset($param['title']) && $param['title']){
                $param['title'] = trim($param['title']);
            }
            if(isset($param['type']) && $param['type']){
                $param['type'] = in_array($param['type'],[1,2,3,4,5]) ? intval($param['type']) : 1;
            }

            //获取菜单数据权限
            if(!empty($param['menus'])){
                $rules = Db::name('admin_rule')->whereIn('menu_id', $rulesParam)->column('pid','id');
                if($rules){
                    //获取1,2级接口权限id
                    $pidIds = array_unique(array_values($rules));
                    $param['rules'] = array_merge($pidIds,array_keys($rules));
                    $param['rules'] =  array_merge($param['rules'],Db::name('admin_rule')->whereIn('id', $pidIds)->column('pid'));
                    $param['rules'] = arrayToString(array_unique($param['rules']));
                }
            }
        } catch (\Exception $e) {
            $this->error = '更新角色失败';
            return false;
        }

        Db::startTrans();
        try {
            unset($param['user_id'], $param['group_id'], $param['dataAuth']);
            $market =empty($request['market'])?[]:$request['market'];
            $marketView =empty($request['market_view'])?[]:$request['market_view'];
            $authField = ['leads', 'customer','market','business','market_view','is_market','order', 'sample', 'min_user'];
            foreach ($authField as $key => $val) {
                if (array_key_exists($val, $request) && !in_array(intval($request[$val]), [1, 2, 3, 4, 5])) {
                    $request[$val] = in_array(intval($request[$val]), [1, 2, 3, 4, 5]) ? intval($request[$val]) : 1;
                }
                unset($param[$val]);
            }
            $bool = $this->where('id', '=', $groupId)->update($param);
            if ($bool >= 0) {
            } else {
                throw new \Exception('更新角色失败');
            }
            $dataArr['group_data'] = $param;

            // 数据权限信息
            $authInfo = Db::name('admin_data_auth')->where('group_id', '=', $groupId)->find();

            // 更新角色数据权限
            $isDataAuth = isset($request['leads']);
            if ($isDataAuth) {
                $authData = [
                    'leads'       => $request['leads'] ?? 1,
                    'customer'    => $request['customer'] ?? 1,
                    'business'    => $request['business'] ?? 1,
                    'order'       => $request['order'] ?? 1,
                    'market'    => json_encode($market,true),
                    'market_view'    => json_encode($marketView,true),
                    'is_market'    => $request['is_market'],
                    'sample'      => $request['sample'] ?? 1,
                    'min_user'    => $request['min_user'] ?? 1,
                    'update_time' => time()
                ];
                if ($authInfo) {
                    // 编辑
                    $bool = Db::name('admin_data_auth')->where('group_id', '=', $groupId)->update($authData);
                    if ($bool >= 0) {
                    } else {
                        throw new \Exception('编辑角色数据权限失败');
                    }
                } else {
                    // 新增
                    $authData['group_id']    = $groupId;
                    $authData['create_time'] = time();
                    $insertId = Db::name('admin_data_auth')->insertGetId($authData);
                    if (!$insertId) {
                        throw new \Exception('添加角色数据权限失败');
                    }
                }
                $dataArr['data_auth_data'] = $authData;
            }
            $dataArr['request_data']   = $request;

            $authNameArr = [
                '1' => '本人',
                '2' => '本人及下属',
                '3' => '本部门',
                '4' => '本部门及下属部门',
                '5' => '全部'
            ];
            // 添加操作记录
            $logContentArr   = [];
            if (isset($param['title']) && $dataInfo['title'] != $param['title']) {
                $logContentArr[] = "将 '角色名称' 由 " . $dataInfo['title'] . " 修改为 " . $param['title'];
            }
           $authLogFieldArr = [
                'leads'    => '线索',
                'customer' => '客户',
                'business' => '商机',
                'order'    => '订单',
                'market'    => '市场',
                'sample'   => '试样',
                'min_user' => '小程序用户',
            ];
            if ($isDataAuth && $authInfo) {
                foreach ($authLogFieldArr as $key => $val) {
                    if ($authData[$key] != $authInfo[$key]) {
                        //$logContentArr[] = "将 '" . $val . "'数据权限 由 " . $authNameArr[$authInfo[$key]] . " 修改为 " . $authNameArr[$authData[$key]];
                    }
                }
            }
            if ($logContentArr) {
                $logContentStr = implode('.|.', $logContentArr);
                $logCode       = json_encode($dataArr, JSON_UNESCAPED_UNICODE);
                $this->addActionRecord($request['user_id'], 'admin_group_update', $groupId, $logContentStr, 'admin', 'group', $logCode);
            }

            Db::commit();

            $this->error = '添加成功';
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
        }

        return false;
    }

    /**
     * 详情
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-13 10:29
     */
    public function getDataInfo(array $request): array
    {
        try {
            $groupId = $request['id'] ?? 0;
            if (!$groupId) {
                $this->error = '参数错误';
                return [];
            }
            $where = [
                ['id', '=', $groupId]
            ];
            $info = $this->where($where)->find();
            if (!$info) {
                $this->error = '信息不存在';
                return [];
            }
            $info = $info->toArray();
            if(isset($info['front_menus']) && $info['front_menus']){
                $info['front_menus'] = stringToArray($info['front_menus']);
            }
            // 获取角色数据权限
            $field    = ['leads', 'customer', 'business','market','order','is_market','market_view','sample', 'min_user'];
            $authInfo = Db::name('admin_data_auth')->where('group_id', '=', $groupId)->field($field)->find();
            if (!$authInfo) {
                $authInfo = [
                    'leads'    => 1,
                    'customer' => 1,
                    'business' => 1,
                    'order'    => 1,
                    'sample'   => 1,
                    'min_user' => 1,
                ];
            }
            $info['dataAuth'] = $authInfo;
            $info['market']=[];
            $info['market_view']=[];
            if(!empty($authInfo['market'])){
                $info['market'] = json_decode($authInfo['market'],true);
                $info['market_view'] = json_decode($authInfo['market_view'],true);
            }
            return $info;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }

    //删除角色
    public function delGroupById($group_id = ''): bool
    {
        $dataInfo = $this->find($group_id);
        if(!$dataInfo){
            $this->error = '该角色不存在或已删除';
            return false;
        }
        if ($dataInfo['types']) {
            $this->error = '系统角色不能删除';
            return false;
        }

        if(Db::name('admin_access')->where('group_id', '=', $group_id)->count()){
            $this->error = '该角色下存在员工不能删除';
            return false;
        }
        $flag = $this->where('id', '=', $group_id)->delete();
        if ($flag) {
            // 删除角色用户关系
            Db::name('admin_access')->where('group_id', '=', $group_id)->delete();
            return true;
        } else {
            $this->error = '删除失败';
            return false;
        }
    }

    /**
     * [getTypeList 获取分类列表]
     * @param  备注：原自定义角色0,人事管理角色3,财务管理角色4，划分至客户管理角色中
     * @return    [array]
     */
    public function getTypeList()
    {
       // $list = ['0' => ['name' => '系统管理角色','pid' => 1],'1' => ['name' => '办公管理角色','pid' => 6],'2' => ['name' => '客户管理角色','pid' => 2],'3' => ['name' => '项目管理角色','pid' => '9']];
        $list = ['0' => ['name' => '系统管理角色','pid' => 0]];
        return $list ? : [];
    }

    /**
     * [getNewGroupPid 兼容9.0.5版本group pid对应关系]
     * @param  备注：原自定义角色0,人事管理角色3,财务管理角色4，划分至客户管理角色中
     * @return    [array]
     */
    protected function getNewGroupPid($pid)
    {
        switch ($pid) {
            case '1' :
                $where[] = ['pid','=',1];
                $where[] = ['types','not in','7'];
                break;
            case '2' :
                $where = function($query) {
                    $query->where([['pid','in','0,2,3,4']])
                        ->whereOr([['type','<>',0],['pid','=',5]]);
                };
                break;
            case '9' :
                $where = function($query) {
                    $query->where([['pid','=',9]])
                        ->whereOr([['types','=',7],['pid','=',1]]);
                };
                break;
            default :
                $where[] = ['pid','=',$pid];
                break;
        }
        return $where ? : [];
    }
}
